﻿namespace LS.Screening.UI.Common
{
    /// <summary>
    /// 重试帮助类
    /// </summary>
    public static class TryHelper
    {
        /// <summary>
        /// 指定次数，重试执行某个方法（此方法在失败情况下会抛出异常），重试次数完成后，抛出此方法的异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">要执行的方法</param>
        /// <param name="times">重试次数</param>
        /// <param name="delaymilliseconds">延时(毫秒)：等于0，表示不延时</param>
        /// <param name="logContent">记录日志内容：为空时不记录日志，不为空则按格式化内容记录</param>
        /// <returns></returns>
        public static T Try<T>(Func<T> func, int times = 3, int delaymilliseconds = 0, string logContent = null)
        {
            Exception ex = null;
            int num = 1;
            while (num <= times)
            {
                try
                {
                    return func();
                }
                catch (Exception ex2)
                {
                    ex = ex2;
                    if (!string.IsNullOrEmpty(logContent))
                    {
                        //LogHelper.Exception(ex, $"Try操作[第{num}次]: [{logContent}] 失败");
                    }

                    num++;
                    if (num > times)
                    {
                        throw;
                    }

                    if (delaymilliseconds > 0)
                    {
                        Thread.Sleep(delaymilliseconds);
                    }
                }
            }

            throw ex;
        }

        /// <summary>
        /// 指定次数，重试执行某个方法（此方法在失败情况下会抛出异常），重试次数完成后，抛出此方法的异常
        /// </summary>
        /// <param name="action">要执行的方法</param>
        /// <param name="times">重试次数</param>
        /// <param name="delaymilliseconds">延时(毫秒)：等于0，表示不延时</param>
        /// <param name="logContent">记录日志内容：为空时不记录日志，不为空则按格式化内容记录</param>
        public static void Try(Action action, int times = 3, int delaymilliseconds = 0, string logContent = null)
        {
            Exception ex = null;
            int num = 1;
            while (num <= times)
            {
                try
                {
                    action();
                    return;
                }
                catch (Exception ex2)
                {
                    ex = ex2;
                    if (!string.IsNullOrEmpty(logContent))
                    {
                        //LogHelper.Exception(ex, $"Try操作[第{num}次]: [{logContent}] 失败");
                    }
                    num++;
                    if (num > times)
                    {
                        throw;
                    }
                    if (delaymilliseconds > 0)
                    {
                        Thread.Sleep(delaymilliseconds);
                    }
                }
            }
            throw ex;
        }
    }
}
